package com.fang.security.core.social.qq.connect;

import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class QQAuth2Template extends OAuth2Template{
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	public QQAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
		super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
	}
	
	@Override
	protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
		String resposeStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
		logger.info("获取acccessToken的响应："+resposeStr);
		String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(resposeStr, "&");
		String accessToken = StringUtils.substringAfterLast(items[0], "=");
		
		return super.postForAccessGrant(accessTokenUrl, parameters);
	}

	@Override
	protected RestTemplate createRestTemplate() {
		RestTemplate restTemplate = super.createRestTemplate();
		restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
		return restTemplate;
	}
	
}
